﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Text.RegularExpressions;
using System.Windows;
using QDP.Platform.ObjService;
using QDP.Platform.Services;
namespace QDP.Platform.Silverlight.Manager
{
    /// <summary> </summary>
    public class ConfigManager
    {
        /// <summary> </summary>
        public ConfigManager()
        {
            Settings = new Dictionary<string, string>();
            Urls = new Dictionary<string, string>();
            Texts = new Dictionary<string, string>();
        }
        /// <summary>获取权限配置对象示例。</summary>
        public ConfigObject Object { get; private set; }
        /// <summary>获取参数集合</summary>
        private Dictionary<string, string> Settings;
        /// <summary>获取地址集合</summary>
        private Dictionary<string, string> Urls;
        /// <summary>获取语言包</summary>
        private Dictionary<string, string> Texts;

        // 平台配置文件路径，不可更改。
        const string CONFIG_FILE_PATH = "config/settings.xml";
        const string APP_CONFIG_SERVER_URL_KEY = "request_config";

        /// <summary>
        /// 
        /// </summary>
        /// <param name="Action"></param>
        public void Read(Action<bool, string> Action)
        {
            Request(CONFIG_FILE_PATH, Action);
        }
        /// <summary>添加一个文字描述信息。</summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void AddText(string key, string value)
        {
            if (Texts.ContainsKey(key))
                Texts[key] = value;
            else
                Texts.Add(key, value);
        }
        /// <summary>添加一个路径描述信息。</summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void AddUrl(string key, string value)
        {
            if (Urls.ContainsKey(key))
                Urls[key] = value;
            else
                Urls.Add(key, value);
        }
        /// <summary>添加一个设置描述信息。</summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void AddSet(string key, string value)
        {
            if (Settings.ContainsKey(key))
                Settings[key] = value;
            else
                Settings.Add(key, value);
        }
        /// <summary>根据用户编号请求专题权限配置信息。</summary>
        /// <param name="userID">要请求权限的用户编号</param>
        /// <param name="Action">请求反馈</param>
        public void RequestConfig(string userID, Action<bool,string> Action)
        {
            string serviceURL = GetUrl(APP_CONFIG_SERVER_URL_KEY);
            var service = ServiceLoader.CreateWCFClient<ObjServiceClient>(serviceURL);
            service.SetLoginUesrCompleted += (sender, args) =>
            {
                if (args.Error != null)
                {
                    Action(false, args.Error.Message);
                    return;
                }
                Object = args.Result;
                Action(true,string.Empty);
            };
            service.SetLoginUesrAsync(userID);
        }
        public void Request(string url,string postData, Action<bool, string> Action)
        {
            WebClient client = new WebClient();
            client.UploadStringCompleted += (s, e) =>
            {
                if (e.Error == null)
                {
                    Action(true, e.Result);
                }
                else
                {
                    Action(false, e.Error.Message);
                }
            };
            try
            {
                if (url.StartsWith("http"))
                {
                    client.DownloadStringAsync(new Uri(url));
                }
                else
                {
                    string baseUrl = client.BaseAddress.Remove(client.BaseAddress.ToLower().LastIndexOf("/") + 1);
                    client.UploadStringAsync(new Uri(baseUrl + url), postData);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(url + ex.Message);
            }
        }

        public void Request(string url, Action<bool, string> Action)
        {
            WebClient client = new WebClient();
            client.DownloadStringCompleted += (s, e) =>
            {
                if (e.Error == null)
                {
                    Action(true, e.Result);
                }
                else
                {
                    Action(false, e.Error.Message);
                }
            };
            try
            {
                if (url.StartsWith("http"))
                {
                    client.DownloadStringAsync(new Uri(url));
                }
                else
                {
                    string baseUrl = client.BaseAddress.Remove(client.BaseAddress.ToLower().LastIndexOf("/") + 1);

                    client.DownloadStringAsync(new Uri(baseUrl + url));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(url + ex.Message);
            }
        }
        /// <summary>通过键值（Key）获得平台相应配置信息，若值不存在则返回空。</summary>
        /// <param name="key">需要获得数据的键值（Key）。</param>
        /// <returns>返回平台相应配置信息，若值不存在则返回空。</returns>
        public string GetSet(string key)
        {
            if (Settings == null || Settings.Count == 0 || Settings.ContainsKey(key) == false) return string.Empty;
            return Settings[key];
        }
        /// <summary>通过键值（Key）获得平台相应地址信息，若值不存在则返回空。</summary>
        /// <param name="key">需要获得数据的键值（Key）。</param>
        /// <returns>返回平台相应地址信息，若值不存在则返回空。</returns>
        public string GetUrl(string key)
        {
            if (Urls == null || Urls.Count == 0 || Urls.ContainsKey(key) == false) return string.Empty;
            string value = Urls[key];
            foreach (Match match in Regex.Matches(value, "{(.+?)}"))
            {
                if (match.Success)
                {
                    string arg = match.Groups[1].Value;
                    string val = GetSet(arg);
                    value = value.Replace("{" + arg + "}", val);
                }
            }
            return value;
        }
        /// <summary>通过键值（Key）获得平台相应语言包信息，若值不存在则返回空。</summary>
        /// <param name="key">需要获得数据的键值（Key）。</param>
        /// <returns>返回平台相应语言包信息，若值不存在则返回空。</returns>
        public string GetText(string key)
        {
            if (Texts == null || Texts.Count == 0 || Texts.ContainsKey(key) == false) return key;
            return Texts[key];
        }
    }
}